'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface Customer {
  id: number;
  name: string;
  email: string;
  phone: string;
  address: string;
  createdAt: string;
  updatedAt: string;
}

export default function CustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchCustomers();
  }, []);

  const fetchCustomers = async () => {
    try {
      const response = await fetch('/api/customers');
      if (!response.ok) {
        throw new Error('获取客户列表失败');
      }
      const data = await response.json();
      setCustomers(data);
    } catch (error) {
      console.error('获取客户数据失败:', error);
      setError('获取客户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const filteredCustomers = customers;

  if (loading) return <div className="p-8">加载中...</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/" className="text-gray-600 hover:text-gray-900">
            ← 返回首页
          </Link>
          <h1 className="text-3xl font-bold">客户管理</h1>
        </div>
        <div className="flex space-x-3">
          <button className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
            导出客户列表
          </button>
          <Link href="/customers/add" className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
            添加客户
          </Link>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="mb-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-gray-800">{customers.length}</div>
          <div className="text-sm text-gray-600">总客户数</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-green-600">
            {customers.filter(c => c.phone && c.phone.length > 0).length}
          </div>
          <div className="text-sm text-gray-600">有联系方式的客户</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-blue-600">
            {new Set(customers.map(c => c.email.split('@')[1])).size}
          </div>
          <div className="text-sm text-gray-600">不同邮箱域名</div>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="p-4 bg-gray-50 border-b">
          <div className="flex space-x-4">
            <input
              type="text"
              placeholder="搜索客户姓名或邮箱..."
              className="px-3 py-2 border border-gray-300 rounded-md w-64"
            />
            <select className="px-3 py-2 border border-gray-300 rounded-md">
              <option>所有客户</option>
              <option>有电话号码</option>
              <option>有地址信息</option>
            </select>
          </div>
        </div>

        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                客户姓名
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                联系方式
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                地址
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                创建时间
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {filteredCustomers.map((customer) => (
              <tr key={customer.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    <div className="flex-shrink-0 h-10 w-10 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold">
                      {customer.name.charAt(0)}
                    </div>
                    <div className="ml-4">
                      <div className="text-sm font-medium text-gray-900">{customer.name}</div>
                      <div className="text-sm text-gray-500">ID: {customer.id}</div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900">{customer.email}</div>
                  <div className="text-sm text-gray-500">{customer.phone || '未填写'}</div>
                </td>
                <td className="px-6 py-4 text-sm text-gray-900">
                  {customer.address ? (
                    <div className="max-w-xs truncate">{customer.address}</div>
                  ) : (
                    '未填写'
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {new Date(customer.createdAt).toLocaleDateString('zh-CN')}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <Link href={`/customers/${customer.id}`} className="text-blue-600 hover:text-blue-900 mr-3">
                    查看详情
                  </Link>
                  <button className="text-green-600 hover:text-green-900">
                    发送消息
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold mb-4">客户分布</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600">VIP客户</span>
              <span className="text-sm font-medium">3 (43%)</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600">活跃客户</span>
              <span className="text-sm font-medium">3 (43%)</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600">不活跃客户</span>
              <span className="text-sm font-medium">1 (14%)</span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold mb-4">消费分析</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600">平均订单价值</span>
              <span className="text-sm font-medium">¥1,429</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600">最高消费客户</span>
              <span className="text-sm font-medium">王五 (¥32,900)</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-600">复购率</span>
              <span className="text-sm font-medium">85.7%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}